package com.neusmart.tongrentang.model;

import com.neusmart.tongrentang.constants.API;
import com.neusmart.tongrentang.constants.HttpMethod;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Custom request param model
 * <p/>
 * roy
 */
public class MParam {

    //
    private API api;
    //
    private Map<String, Object> params = new HashMap<>();
    //
    private boolean loadHint;

    public MParam() {
    }

    public MParam(API api, boolean loadHint) {
        this.api = api;
        this.loadHint = loadHint;
    }

    public API getApi() {
        return api;
    }

    public void setApi(API api) {
        this.api = api;
    }

    public Map<String, Object> getParams() {
        return params;
    }

    public void setParams(Map<String, Object> params) {
        this.params = params;
    }

    public void addParam(String key, Object value) {
        params.put(key, value);
    }

    public void addParams(Map<String, Object> params) {
        this.params.putAll(params);
    }

    public String getRequestUrl() {
        if ((api.getHttpMethod() == HttpMethod.GET || api.getHttpMethod() == HttpMethod.POST) && params.size() > 0) {
            StringBuilder sb = new StringBuilder(api.getUrl() + "?");
            for (String key : params.keySet()) {
                sb.append(key + "=");
                if (params.get(key) == null)
                    sb.append("&");
                else
                    sb.append(URLEncoder.encode(params.get(key).toString()) + "&");
            }
            sb.deleteCharAt(sb.length() - 1);
            return sb.toString();
        }
        return api.getUrl();
    }

    public boolean isLoadHint() {
        return loadHint;
    }

    public void setLoadHint(boolean loadHint) {
        this.loadHint = loadHint;
    }
}
